/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.controllers;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.database.Database;
import org.database.DatabaseEmre;
import org.database.DatabaseYakup;
import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.property.Estate;
import org.property.House;
import org.property.Sale;
import org.users.Agent;
import org.users.Customer;
import org.users.Supervisor;

/**
 *
 * @author yakup
 */
@ManagedBean(name = "supervisorbean")
@ViewScoped
public class SupervisorBean implements Serializable {

    private Supervisor supervisor;
    private Agent agent;
    private String city;
    private String suburb;
    private String type;
    private static List<Customer> customers = new LinkedList<Customer>();
    private static List<Sale> sales = new LinkedList<Sale>();
    private static Sale selectedSale = new Sale();
    private String roomType;
    private Map<String, String> roomTypes = new HashMap<String, String>();
    private LinkedList<String> uploadedEstateImages = new LinkedList<String>();
    private static Customer customer = new Customer();
    private Map<String, String> cities = new HashMap<String, String>();
    private Map<String, String> types = new HashMap<String, String>();
    private Map<String, Map<String, String>> suburbsData = new HashMap<String, Map<String, String>>();
    private Map<String, String> suburbs = new HashMap<String, String>();
    private String password = "";
    private static Agent selectedAgent = new Agent();
    private static House selectedHouse = new House();
    private List<House> houses;
    private House house = new House();
    private LinkedList<Agent> agents = new LinkedList<Agent>();
    private Estate estate;
    private static Estate selectedEstate = new Estate();
    private LinkedList<Estate> estates = new LinkedList<Estate>();
    private static int numofObjects = 0;
    private List<String> images;
    private List<String> imagesHouse;
    private String effect = "fade";

    public SupervisorBean() {
        try {
            //if(numofObjects==0)
            numofObjects++;
            supervisor = new Supervisor();
            agent = new Agent();
            houses = new ArrayList<House>();

            // customers = new LinkedList<Customer>();
            DatabaseEmre dbe1 = new DatabaseEmre();

            dbe1.connect();
            houses = dbe1.getHouseList();
            //customers = dbe1.getCustomerList();
            dbe1.disconnect();

            estate = new Estate();
            types.put("Sale", "1");
            types.put("Rent", "2");


            //        int id, String type, int price, char isConstruction, char isCountryside, int perceptOfConstruction, String district, String province,  String address, String agentId, String customerId) {
            //  estates.add(new Estate(1, "Rent", 500, 'Y', 'Y', 50, "Gebze", "Kocaeli", "Şekerpınar Mah", "null", "null"));
            //   estates.add(new Estate(2, "Sale", 50000, 'Y', 'Y', 50, "Kaynarca", "Sakarya", "Yılmaz Vural Caddesi", "null", "null"));
            //  estates.add(new Estate(3, "Rent", 300, 'Y', 'Y', 25, "Kaynarca", "Sakarya", "Yılmaz Vural Caddesi", "null", "null"));
            Database db = new Database();
            db.connect();
            agents = db.getAgentList();
            cities = db.getCitiesMap();
            suburbsData = db.getSuburbsMap();

            db.disconnect();
            DatabaseYakup db2 = new DatabaseYakup();
            db2.connect();
            estates = db2.getEstateList();
            roomTypes = db2.getRoomTypes();
            db2.disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @PostConstruct
    public void init() {
        images = new ArrayList<String>();
        imagesHouse = new ArrayList<String>();
        images = selectedEstate.getImageList();
        imagesHouse = selectedHouse.getImageList();

    }

    public List<Sale> getSales() {
        return sales;
    }

    public void setSales(List<Sale> sales) {
        this.sales = sales;
    }

    public Sale getSelectedSale() {
        return selectedSale;
    }

    public void setSelectedSale(Sale selectedSale) {
        this.selectedSale = selectedSale;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }

    public String getRoomType() {
        return roomType;
    }

    public void setRoomType(String roomType) {
        this.roomType = roomType;
    }

    public Map<String, String> getRoomTypes() {
        return roomTypes;
    }

    public void setRoomTypes(Map<String, String> roomTypes) {
        this.roomTypes = roomTypes;
    }

    public List getUploadedEstateImages() {
        return uploadedEstateImages;
    }

    public void setUploadedEstateImages(LinkedList uploadedEstateImages) {
        this.uploadedEstateImages = uploadedEstateImages;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Map<String, String> getTypes() {
        return types;
    }

    public void setTypes(Map<String, String> types) {
        this.types = types;
    }

    public List<House> getHouses() {
        return houses;
    }

    public void setHouses(List<House> houses) {
        this.houses = houses;
    }

    public House getSelectedHouse() {
        return selectedHouse;
    }

    public void setSelectedHouse(House selectedHouse) {
        SupervisorBean.selectedHouse = selectedHouse;
    }

    public House getHouse() {
        return house;
    }

    public void setHouse(House house) {
        this.house = house;
    }

    public String getEffect() {
        return effect;
    }

    public void setEffect(String effect) {
        this.effect = effect;
    }

    public List<String> getImages() {
        return images;
    }

    public void setImages(List<String> images) {
        this.images = images;
    }

    public List<String> getImagesHouse() {
        return imagesHouse;
    }

    public void setImagesHouse(List<String> imagesHouse) {
        this.imagesHouse = imagesHouse;
    }

    public LinkedList<Agent> getAgents() {
        return agents;
    }

    public void setAgents(LinkedList<Agent> agents) {
        this.agents = agents;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Supervisor getSupervisor() {
        return supervisor;
    }

    public void setSupervisor(Supervisor supervisor) {
        this.supervisor = supervisor;
    }

    public void login() throws SQLException, ClassNotFoundException, IOException {
        Database db = new Database();
        db.connect();
        System.out.print("metod çalıştı");
//        if(supervisor.getUserName().equals("ozdeny") && supervisor.getPassword().equals("1234"))
//            FacesContext.getCurrentInstance().getExternalContext().redirect("Supervisor.xhtml");
//        else
//            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Kullanıcı adı veya parola yanlış"));
//      
        String id = db.loginSupervisor(supervisor);

        if (!id.equals("none")) {
            supervisor = db.getSupervisor(id);
            FacesContext.getCurrentInstance().getExternalContext().redirect("Supervisor.xhtml");
            System.out.print("şifre doğru");
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Kullanıcı adı veya parola yanlış"));
            System.out.print("şifre yanlış");

        }
        db.disconnect();


    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSuburb() {
        return suburb;
    }

    public void setSuburb(String suburb) {
        this.suburb = suburb;
    }

    public Map<String, String> getCities() {
        return cities;
    }

    public void setCities(Map<String, String> cities) {
        this.cities = cities;
    }

    public Map<String, Map<String, String>> getSuburbsData() {
        return suburbsData;
    }

    public void setSuburbsData(Map<String, Map<String, String>> suburbsData) {
        this.suburbsData = suburbsData;
    }

    public Map<String, String> getSuburbs() {
        return suburbs;
    }

    public void setSuburbs(Map<String, String> suburbs) {
        this.suburbs = suburbs;
    }

    public void handleCityChange() {
        if (city != null && !city.equals("")) {
            suburbs = suburbsData.get(city);
        } else {
            suburbs = new HashMap<String, String>();
        }
    }

    public Agent getAgent() {
        return agent;
    }

    public void setAgent(Agent agent) {
        this.agent = agent;
    }

    public Agent getSelectedAgent() {
        return selectedAgent;
    }

    public void setSelectedAgent(Agent selectedAgent) {
        this.selectedAgent = selectedAgent;
    }

    public LinkedList<Estate> getEstates() {
        return estates;
    }

    public void setEstates(LinkedList<Estate> estates) {
        this.estates = estates;
    }

    public Estate getSelectedEstate() {
        return selectedEstate;
    }

    public void setSelectedEstate(Estate selectedEstate) {
        this.selectedEstate = selectedEstate;
    }

    public Estate getEstate() {
        return estate;
    }

    public void setEstate(Estate estate) {
        this.estate = estate;
    }

    public void addAgent() {
        try {
            System.out.println(agent.getAddressResume() + agent.getAddressDistrict());
            Database db = new Database();
            db.connect();
            agent.setAddressDistrict(suburb);
            agent.setAddressProvince(city);
            password = db.addAgent(agent);
            FacesMessage msg = new FacesMessage("Agent added with password:" + password);
            FacesContext.getCurrentInstance().addMessage(null, msg);
            db.disconnect();
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void deleteAgent() {
        try {
            System.out.print(selectedAgent.getTC_ID() + "id");

            Database db = new Database();
            db.connect();
            db.deleteAgent(selectedAgent);
            agents = db.getAgentList();
            db.disconnect();
            DatabaseYakup db2 = new DatabaseYakup();
            db2.connect();

            db2.disconnect();
            FacesMessage msg = new FacesMessage("Agent deleted successfully");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void updateAgent() {
        try {

            DatabaseYakup db = new DatabaseYakup();

            db.connect();
            selectedAgent.setAddressDistrict(suburb);
            selectedAgent.setAddressProvince(city);
            db.updateAgent(selectedAgent);
            FacesMessage msg = new FacesMessage("Agent successfully updated");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            db.disconnect();

        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void handleFileUpload(FileUploadEvent event) throws IOException {
        UploadedFile file = event.getFile();
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        File newFile = new File(extContext.getRealPath("//Images") + "//" + event.getFile().getFileName());
        System.out.println(System.getProperty("user.home") + File.separator + file.getFileName());
        System.out.println(extContext.getRealPath("//Images") + "//" + event.getFile().getFileName());
        FileOutputStream fileOutputStream = new FileOutputStream(newFile);
        uploadedEstateImages.add(event.getFile().getFileName());
        byte[] buffer = new byte[6124];

        int bulk;
        InputStream inputStream = event.getFile().getInputstream();
        while (true) {
            bulk = inputStream.read(buffer);
            if (bulk < 0) {
                break;
            }
            fileOutputStream.write(buffer, 0, bulk);
            fileOutputStream.flush();
        }

        fileOutputStream.close();
        inputStream.close();

        FacesMessage msg = new FacesMessage("Succesful",
                event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);


    }

    public void addEstate() {
        try {
            estate.setImageList(uploadedEstateImages);
            estate.setDistrict(suburb);
            estate.setProvince(city);
            estate.setType(type);


            DatabaseYakup db = new DatabaseYakup();
            db.connect();
            db.addEstate(estate);
            db.disconnect();
            uploadedEstateImages.clear();
            FacesMessage msg = new FacesMessage("Estate added successfully");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }




    }

    public void showEstateDetails() throws IOException {
        images = selectedEstate.getImageList();
        if (images.isEmpty()) {
            System.out.print("liste bos");
        } else {
            for (String i : images) {
                System.out.print(i);
            }

        }




        FacesContext.getCurrentInstance().getExternalContext().redirect("SupervisorEstateDetail.xhtml");
        //   return  "testestatedetails.xhtml";
    }

    public void deleteEstate() throws ClassNotFoundException, SQLException {


        DatabaseYakup db = new DatabaseYakup();
        db.connect();
        db.deleteEstate(selectedEstate);
        estates = db.getEstateList();
        db.disconnect();
        FacesMessage msg = new FacesMessage("Estate deleted successfully");
        FacesContext.getCurrentInstance().addMessage(null, msg);


    }

    public void updateEstate() {
        try {
            DatabaseYakup db = new DatabaseYakup();
            db.connect();
            selectedEstate.setDistrict(suburb);
            selectedEstate.setProvince(city);
            selectedEstate.setType(type);
            db.updateEstate(selectedEstate);
            db.disconnect();

            FacesMessage msg = new FacesMessage("Estate updated successfully");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void addHouse() {
        try {
            //    System.out.println(house.getIsCombi());
            System.err.println(house.getDescription());
            house.setImageList(uploadedEstateImages);
            house.setType(type);
            house.setRoom_type(roomType);
            house.setDistrict(suburb);
            house.setProvince(city);
            DatabaseYakup dbe = new DatabaseYakup();
            dbe.connect();

            dbe.addHouse(house);
            dbe.disconnect();
            FacesMessage msg = new FacesMessage("House added successfully");
            FacesContext.getCurrentInstance().addMessage(null, msg);

            //      house.setRoom_type();
            //      house.setRoom_type();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }





    }

    public void showHouseDetails() throws IOException {
        imagesHouse = selectedHouse.getImageList();

        FacesContext.getCurrentInstance().getExternalContext().redirect("SupervisorHouseDetail.xhtml");
    }

    public void deleteHouse() {
        try {
            DatabaseEmre dbe = new DatabaseEmre();
            dbe.connect();
            dbe.deleteHouse(selectedHouse);
            houses = dbe.getHouseList();
            dbe.disconnect();
            FacesMessage msg = new FacesMessage("House is deleted");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void updateHouse() {
        try {
            selectedHouse.setRoom_type(roomType);
            selectedHouse.setDistrict(suburb);
            selectedHouse.setProvince(city);
            selectedHouse.setType(type);
            DatabaseEmre dbe = new DatabaseEmre();
            dbe.connect();
            dbe.updateHouse(selectedHouse);
            dbe.disconnect();
            FacesMessage msg = new FacesMessage("House is updated successfully");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String listCustomers() {
        try {
            DatabaseEmre dbe = new DatabaseEmre();
            dbe.connect();
            customers = dbe.getCustomerList();
            System.out.println("------------------>" + customers.size());
            dbe.disconnect();
            FacesContext.getCurrentInstance().getExternalContext().redirect("SupervisorSearchCustomer.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "SupervisorSearchCustomer";



    }

    public void generateDailyReport() {
        try {
            DatabaseYakup dby = new DatabaseYakup();
            dby.connect();
            sales = dby.getDailySellList();
            dby.disconnect();
            FacesContext.getCurrentInstance().getExternalContext().redirect("DailyReport.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(SupervisorBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }
}
